package com.example.mandatory;

import java.io.IOException;
import java.util.List;
import java.util.Locale;

import android.app.Activity;
import android.content.Context;
import android.location.Address;
import android.location.Criteria;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.view.Menu;
import android.widget.TextView;

public class WeatherActivity extends Activity {
	
	LocationManager mLocationManager;
	TextView tv;
	Location mLocation;
	String city = null;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
		tv =(TextView)findViewById(R.id.textView1);
		
		//location
		LocationManager mLocationManager;
		mLocationManager =(LocationManager)getSystemService(Context.LOCATION_SERVICE);

		//criteria of searching best way of finding location (GPS/Wi-Fi)
		Criteria criteria = new Criteria();
		criteria.setAccuracy(Criteria.ACCURACY_FINE);
		criteria.setPowerRequirement(Criteria.POWER_LOW);
		String locationprovider = mLocationManager.getBestProvider(criteria, true);

		
		//get last known Location
	    mLocation= mLocationManager.getLastKnownLocation(locationprovider);	    
		mLocationManager.requestLocationUpdates(locationprovider, 5000, (float) 2.0, myLocL);
		
		List<Address> addresses;
		try{
			Geocoder mGC = new Geocoder(this,Locale.ENGLISH);
			addresses = mGC.getFromLocation(mLocation.getLatitude(), mLocation.getLongitude(), 1);

			if(addresses != null){
				Address currentAddr = addresses.get(0);
				StringBuilder mSB = new StringBuilder("Address:\n");
				for(int i=0; i<currentAddr.getMaxAddressLineIndex();i++){
					mSB.append(currentAddr.getLocality()).append("\n");
			
					
					//HERE NIGGER!  tv.setText(currentAdds.getLocality() (returns city name)
					
					//		currentAddr.getLocality();
				}
				
				city = currentAddr.getLocality();
				tv.setText(city);
			}
		}catch(IOException e){tv.setText(e.getMessage());}
	
	}
		
	private final LocationListener myLocL = new LocationListener(){
		
		@Override
		public void onLocationChanged(Location location){
			mLocation= location;
			//Showupdate();			
		}
		private void Showupdate() {
			// TODO Auto-generated method stub
			
			tv.setText("Last location lat:"+mLocation.getLatitude()+" long:"+mLocation.getLongitude());
		}
		@Override
		public void onProviderDisabled(String provider) {}
		@Override
		public void onProviderEnabled(String provider) {}
		@Override
		public void onStatusChanged(String provider, int status, Bundle extras) {	}
		
	};
	
	
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.weather, menu);
		return true;
	}

}
